package yannuo.dao.impl;

import yannuo.dao.EmpDao;
import yannuo.pojo.Emp;
import yannuo.util.DriudUtil;

import java.sql.*;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class EmpDaoImpl implements EmpDao {
    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;
    @Override
    public int getEmpCount() {
        int count = 0;
        try {
            conn = DriudUtil.getConnection();
            pstmt = conn.prepareStatement("select count(*) from emp");
            rs = pstmt.executeQuery();
            if(rs.next()){
                count = rs.getInt(1);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            DriudUtil.closeAll(rs,pstmt,conn);
        }
        return count;
    }

    @Override
    public List<Emp> pageQueryAllEmps(int beginNum, int pageSize) {
        List<Emp> emps = new ArrayList<>();
        Emp emp = null;

        try {
            conn = DriudUtil.getConnection();
            pstmt = conn.prepareStatement("select * from emp limit ?,?");
            pstmt.setInt(1,beginNum);
            pstmt.setInt(2,pageSize);
            rs = pstmt.executeQuery();
            while(rs.next()){
                //从结果集中取出数据 并 封装到对象 再添加到集合中
                emp = new Emp(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getDate(5),rs.getDouble(6),rs.getDouble(7),rs.getInt(8));
                emps.add(emp);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            DriudUtil.closeAll(rs,pstmt,conn);
        }
        return emps;
    }
}
